package cyou.breathe.blog.email;

import cyou.breathe.blog.email.response.EmailSendResponse;
import cyou.breathe.blog.lock.DistributeLock;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Properties;

import static cyou.breathe.blog.base.response.ResponseCode.SYSTEM_ERROR;
import static cyou.breathe.blog.email.constant.EmailConstant.CONTENT;
import static cyou.breathe.blog.email.constant.EmailConstant.TITLE;

/**
 * @author: breathe
 * @createTime: 2025-08-26
 */
@Service
@Slf4j
@Setter
public class EmailServiceImpl implements EmailService {
    private String user;

    private String code;

    private String host;

    private boolean auth;

    private int port;

    public boolean smtpSslEnable;
    @Override
    @DistributeLock(scene = "SEND_EMAIL", keyExpression = "#email")
    public EmailSendResponse sendEmail(String email, String code) {

        EmailSendResponse emailSendResponse = new EmailSendResponse();

        // 从配置类获取配置
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", auth);
        // 启用 SSL/TLS
        properties.put("mail.smtp.ssl.enable", smtpSslEnable);
        // 创建邮件会话
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, EmailServiceImpl.this.code);
            }
        });

        try {
            // 创建邮件
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(user));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            message.setSubject(TITLE);
            message.setText(String.format(CONTENT, code));

            // 发送邮件
            Transport.send(message);
            emailSendResponse.setSuccess(true);
        } catch (MessagingException e) {
            //false
            emailSendResponse.setSuccess(false);
            emailSendResponse.setResponseCode(SYSTEM_ERROR.name());
            emailSendResponse.setResponseMessage(StringUtils.substring(e.toString(), 0, 1000));
        }
        return emailSendResponse;
    }
}
